package cn.tude.websocket.websocket.util;

import cn.tude.websocket.user.service.UserService;
import cn.tude.websocket.user.service.impl.UserServiceImpl;
import cn.tude.websocket.websocket.service.WebSocketService;
import cn.tude.websocket.websocket.service.impl.WebSocketServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;


@Slf4j
public class WebSocketUtil {
    public static HashMap<String, Session> sessions=new HashMap<>();

    public static Map<String, String> form_to_Sessions=new ConcurrentHashMap<>();

    public static WebSocketService webSocketService=new WebSocketServiceImpl();

    public static ObjectMapper jsonMapper = new ObjectMapper();

    public static void sendMessage(Session session,String message){
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        try {
            basic.sendText(message);
        } catch (IOException e) {
            log.error("sendMessage IOException ",e);
        }
    }

    //遍历所有from-to  看是否存过这一对
    public static Boolean foreachAllfromto(String fromU,String toU){
        AtomicBoolean b=new AtomicBoolean(false);
        form_to_Sessions.forEach((k,v)->{
            if (k.equals(fromU)&&v.equals(toU) || k.equals(toU)&&v.equals(fromU)){
                //我想要改掉b的值
                b.set(true);
            }
        });
        Boolean bb=b.get();
        return bb;
    }

}
